let timerThrottle;
let timerDebounce;
let flag;
export const $tool = {
	//图片预览
	previewImage: (url, index = 0) => {
		if (typeof url === 'string') {
			uni.previewImage({
				current: 0,
				urls: [url]
			})
		}
		if (typeof url === 'object' || typeof url === 'array') {
			uni.previewImage({
				current: index,
				urls: url
			})
		}
	},
	//提示
	toast: (str, icon = 'none') => {
		uni.showToast({
			title: str,
			icon: icon
		})
	},
	//复制
	copy: (str) => {
		uni.setClipboardData({
			data: str
		})
	},
	isWeChatEnv:()=> {
		const userAgent = navigator.userAgent.toLowerCase();
		return /micromessenger/.test(userAgent);
	},
	//节流函数 
	throttle: (func, wait = 500, immediate = true) => {
		if (immediate) {
			if (!flag) {
				flag = true
				typeof func === 'function' && func()
				timerThrottle = setTimeout(() => {
					flag = false
				}, wait)
			}
		} else if (!flag) {
			flag = true
			timerThrottle = setTimeout(() => {
				flag = false
				typeof func === 'function' && func()
			}, wait)
		}
	},
	//防抖函数
	debounce: (func, wait = 500, immediate = false) => {
		if (timerDebounce !== null) clearTimeout(timerDebounce)
		if (immediate) {
			const callNow = !timerDebounce
			timerDebounce = setTimeout(() => {
				timerDebounce = null
			}, wait)
			if (callNow) typeof func === 'function' && func()
		} else {
			timerDebounce = setTimeout(() => {
				typeof func === 'function' && func()
			}, wait)
		}
	},
	replaceUrlParam:(key, value)=> {
	    const url = new URL(globalThis.location.href);
		const queryArr=url.hash.split('?');
		const hashParams = new URLSearchParams(queryArr[1]?queryArr[1]:''); 
	    hashParams.set(key, value);
	    url.hash = queryArr[0]+'?'+hashParams.toString();
	    globalThis.history.replaceState({}, '', url.href);
	}
}